package com.iman.locker.view;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.iman.locker.R;
import com.iman.locker.model.AppInfo;
import com.iman.locker.persistence.DbHelper;
import com.iman.locker.view.adapter.AppInfoAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 应用列表
 * Created by esirong on 2015-12-04.
 */
public class AppsActivity extends BaseActivity {
    private ListView listView;
    private TextView lockCounter;
    private AppInfoAdapter adapter;
    private LinkedList<AppInfo> itemLinkedList = new LinkedList<>();//所有应用数据列表
    private ArrayList<Integer> checkedItem = new ArrayList<>();//已被锁定的记录索引
    TextView toolbarTitle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apps);

        lockCounter = (TextView) findViewById(R.id.lock_counter);
        //设置listView
        listView = (ListView) findViewById(R.id.list);
        initAppLockedList();
    }

    private void initAppLockedList() {
        initListViewAppInfo();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int count = listView.getCheckedItemCount();
                AppInfo appInfo = adapter.getItem(position);
                if (listView.isItemChecked(position)) {
                    save(appInfo);
                } else {
                    delete(appInfo);
                }
                setLockCounter(count);
            }
        });
    }

    //初始化listView的列表
    private void initListViewAppInfo() {
        //用来存储获取的应用信息数据
        new LoadLockedAppList().execute();
    }
    //保存需要保护的应用
    private void save(AppInfo info) {
        DbHelper.getInstance().add(info);
    }

    //删除不霜保护的应用
    private void delete(AppInfo info) {
        DbHelper.getInstance().delete(info);
    }

    class LoadLockedAppList extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
        }

        @Override
        protected Void doInBackground(Void... params) {
            List<AppInfo> result = getLauncherAppInfoList();
            itemLinkedList.addAll(result);
            checkedItem.addAll(getCheckedAppLockedList());

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            adapter = new AppInfoAdapter(AppsActivity.this, itemLinkedList);
            listView.setAdapter(adapter);
            listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);//多选模式
            initCheckedItem(checkedItem);
            findViewById(R.id.progressBar).setVisibility(View.GONE);
        }
    }

    //初始化listView列表已选中的条目
    private void initCheckedItem(ArrayList<Integer> checkedItem) {
        if (checkedItem == null) {
            return;
        }
        setLockCounter(checkedItem.size());
        for (int i = 0; i < checkedItem.size(); i++) {
            int position = checkedItem.get(i);
            listView.setItemChecked(position, true);
        }
    }
    /**
     * 获取所有可以启动的应用信息列表
     *
     * @return 应用列表
     */
    private List<AppInfo> getLauncherAppInfoList() {
        PackageManager packageManager = getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<AppInfo> appInfoList = new ArrayList<>();
        List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(
                mainIntent, 0);
        Collections.sort(resolveInfo, new ResolveInfo.DisplayNameComparator(packageManager));
        for (ResolveInfo reInfo : resolveInfo) {
            //忽略自身
            if (reInfo.activityInfo.packageName.equals(getPackageName())) {
                continue;
            }
            String activityName = reInfo.activityInfo.name; // 获得该应用程序的启动Activity的name
            String pkgName = reInfo.activityInfo.packageName; // 获得应用程序的包名
            String appLabel = (String) reInfo.loadLabel(packageManager); // 获得应用程序的Label
            Drawable icon = reInfo.loadIcon(packageManager); // 获得应用程序图标
            // 为应用程序的启动Activity 准备Intent
            Intent launchIntent = new Intent();
            launchIntent.setComponent(new ComponentName(pkgName,
                    activityName));
            // 创建一个AppInfo对象，并赋值
            AppInfo appInfo = new AppInfo();
            appInfo.label = appLabel;
            appInfo.packageName = pkgName;
            appInfo.icon = icon;
            appInfoList.add(appInfo); // 添加至列表中

        }
        return appInfoList;
    }
    //获取listView列表中默认被选中的条目索引
    private ArrayList<Integer> getCheckedAppLockedList() {
        List<AppInfo> list = DbHelper.getInstance().findAll();
        ArrayList<Integer> check = new ArrayList<>();
        if (list == null || list.isEmpty()) {
            return check;
        }
        //检查需要的保护的应用是否包含在listView数据列表中。并将所在索引记录下来
        for (AppInfo appInfo : list) {
            if (itemLinkedList.contains(appInfo)) {
                check.add(itemLinkedList.indexOf(appInfo));
            }
        }
        return check;
    }


    //显示已锁程序数量
    private void setLockCounter(int number) {
        String result = number+"/"+itemLinkedList.size();
        lockCounter.setText(String.format(getString(R.string.lock_counter), result));
    }
}
